package com.andova

import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.andova.manager.CacheManager
import com.andova.sample.databinding.AcTimeQuantumBinding
import com.andova.widget.timequantum.Time
import com.andova.widget.timequantum.TimeQuantumView
import com.google.gson.Gson

class Widget_TimeQuantum : AppCompatActivity(), TimeQuantumView.OnTimeQuantumListener {
    private var mBinding: AcTimeQuantumBinding? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        CacheManager.singleton().initialize(application)
        mBinding = AcTimeQuantumBinding.inflate(layoutInflater)
        setContentView(mBinding?.root)
        mBinding?.tqv?.setListener(this@Widget_TimeQuantum)
    }

    private fun getPeriods(): Map<Int, List<Time>> {
        val tqs = mutableMapOf<Int, List<Time>>()
        for (i in 0..6) {
            val times = CacheManager.singleton().getStringSet(i.toString()) ?: continue
            val set = mutableListOf<Time>()
            for (time in times) set.add(Gson().fromJson(time, Time::class.java))
            tqs[i] = set
        }
        return tqs
    }

    override fun onReadied() {
        val periods = getPeriods()
        mBinding?.tqv?.apply {
            setPeriods(periods)
            setReadOnly(periods.isNotEmpty())
        }
    }

    override fun onChanged(tqs: Map<Int, List<Time>>) {
        println("changed:$tqs")
        for (tq in tqs) {
            val set = mutableSetOf<String>()
            for (time in tq.value) set.add(Gson().toJson(time))
            CacheManager.singleton().edit(tq.key.toString(), set)
        }
    }

    override fun onWindowFocusChanged(hasFocus: Boolean) {
        super.onWindowFocusChanged(hasFocus)
        if (!hasFocus) return
        window.decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                or View.SYSTEM_UI_FLAG_FULLSCREEN
                or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY)
    }
}